import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import {Message} from 'element-ui'

var instance = axios.create({
	baseURL:"http://127.0.0.1:80",
	}
)

instance.interceptors.request.use(
    config => {    
        let token = window.localStorage.getItem('token');
        console.log("每次请求前读取 Token=" + token) 
        if (token) {
            config.headers.Authorization = "Bearer " + token;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

//响应拦截
instance.interceptors.response.use(
	//第一个参数是一个匿名函数做为参数变量，正常响应HTTP状态码200
	response=>{
		console.log("正常响应 HTTP状态码"+response.status);
		
		return response;
	},
	
	//第二个参数是一个匿名函数做为参数变量，非正常响应HTTP状态码200
	error=>{
		if(error.response){//如果没有
			switch(error.response.status){
				case 401:
					Message.error("401 无权限...");
					window.localStorage.setItem("token","");
				break;
				case 403:
					Message.error("402 无权限...");
				break;
				default:
					Message.error(error.response.status+" 系统建设中");
				break;
			}
		}
		return Promise.reject(error.response.data)
	}
)


//提交4种方式 get post kv postFile postJson

//get 封装支持两种方式
//请求路径url /api/adm/clz/findAll?id=100 $get("api/adm/clz/findById?id=100")
//请求路径url /api/adm/clz/findAll $get("api/adm/clz/findById",{id:100})
//参数:对象格式

//请求路径url /api/adm/clz/findAll 
 
export let $get = (url,obj)=>{
	return instance.get(url,{params:obj})

}

//post 键值对
export let $postkv = (url,obj)=>{
	let head = {henders:{
		'Content-type':'application/x-www-from-urlencoded;charset=url=utf8',
		},
	}
	let kv =qs.stringify(obj)
	return instance.post(url,kv,head)
}

//post文件
export let $postfile = (url,formdate)=>{
	return instance.post(url,formdate,
	{headers:{'Content-type':'multipart/from-data'}})
}

//post Json
export let $postjson = (url,obj)=>{
	return instance.post(url,obj,{headers:{'Content-type':'application/json;charset=url=utf8'}})
}